import axios, {type AxiosResponse} from 'axios'
import {ElMessage} from 'element-plus'
import {getEnumByCode, ErrorTypes} from '../global/enums/RetInfoEnum.ts'
import {useTokenStore} from "@/stores/useTokenStore.ts";
import settings from "@/settings.ts"
//创建axios实例
const request = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 20000,
})

//请求拦截器
request.interceptors.request.use((config) => {
  const tokenStore = useTokenStore()
  //若存在token 则请求头上携带token
  if (tokenStore.token) {
    config.headers[settings.TOKEN_NAME] = tokenStore.token
  }
  return config
})

//响应拦截器
request.interceptors.response.use(
  (response:AxiosResponse) => {

    // 如果是blob响应，返回AxiosResponse格式的完整响应
    if (response.config.responseType === 'blob') {
      return response; // 直接返回完整响应对象
    }

    const {code, msg} = response.data
    if (code !== 'M000') {
      ElMessage({
        type: 'error',
        message: msg,
      })
      return Promise.reject(response.data)
    }
    return Promise.resolve(response.data)
  },
  (error) => {

    //处理网络错误
    const errorInfo = getEnumByCode(error.response.status)
    const msg = errorInfo ? ErrorTypes[errorInfo].message : error.message
    ElMessage({
      type: 'error',
      message: msg,
    })
    return Promise.reject(error)
  },
)
export default request
